package com.teradata.bigdata.redis;

import cn.hutool.db.nosql.redis.RedisDS;
import cn.hutool.json.JSONUtil;
import redis.clients.jedis.Jedis;
import java.util.*;

/**
 * @Project:
 * @Description:
 * @Version 1.0.0
 * @Throws SystemException:
 * @Author: <li>2019/11/26/026 Administrator Create 1.0
 * @Copyright ©2018-2019 al.github
 * @Modified By:
 */
public class ExportFromRedis {

    public static void main(String[] args) {
        Jedis jedis = RedisDS.create().getJedis();
        TeradataUtil teradataUtil = new TeradataUtil();
        Set<String> keys = jedis.keys("td:travel:realtime:day:*");
        List<TourScenicAreaVo> list = new ArrayList<>();
        keys.stream().forEach((String x) ->{
            Map<String, String> fields=jedis.hgetAll(x);
            String sceneryId = x.substring(x.lastIndexOf(":")+1);
            String maxField= (String) getMaxKey(fields);
            String value = fields.get(maxField);
            if (JSONUtil.isJson(value)){
                RealTimeCount count=JSONUtil.toBean(value,RealTimeCount.class);
                TourScenicAreaVo tourScenicAreaVo = new TourScenicAreaVo(sceneryId,count);
                list.add(tourScenicAreaVo);
            }
        });
        try {
            teradataUtil.deleteRow();
            teradataUtil.batchInsert(list);
        } catch (Exception e) {
            e.printStackTrace();
        }
        jedis.close();
    }

    public static Object getMaxKey(Map<String, String> map) {
        if (map == null) {
            return null;
        }
        Set<String> set = map.keySet();
        Object[] obj = set.toArray();
        Arrays.sort(obj);
        return obj[obj.length-1];
    }
}
